﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AutomationTools;
using AutomationTools.Procedimentos;
using AutomationTools.Procedimentos.Busca;
using AutomationTools.Procedimentos.Iteracao;
using AutomationTools.Procedimentos.Acao.Transformacao;
using System.Collections;
using System.IO;
using AutomationTools.Procedimentos.Leitura;

namespace AutomationToolsSample
{
    public partial class Form5 : Form
    {
        public Form5()
        {
            InitializeComponent();
        }

        private void btnPesquisar_Click(object sender, EventArgs e)
        {
            txtResult.Text = Pesquisar(txtPesquisar.Text);
        }

        private string Pesquisar(string tracecode)
        {
            ParametrosRequest nill = new ParametrosRequest();
            nill.Add(new ParametroRequest("tracknbr", tracecode));

            ProcedimentoController controller = new ProcedimentoController(
                new Request("http://app3.hongkongpost.com/CGI/mt/genresult.jsp", nill, Request.EnumFormMethod.POST)
                , new RegexParseObject<Encomenda>()
                , new ExecutarFunction<Encomenda>(delegate(Encomenda x)
            {
                x.StatusEncomenda = new String(x.StatusEncomenda.ToCharArray().Reverse().ToArray());
                return x;
            })
            );

            var result = (Encomenda)controller.ExecutarProcedimentos();

            return result.StatusEncomenda == null ? "Encomenda não encontrada" : result.StatusEncomenda;
        }

        private void Form5_FormClosed(object sender, FormClosedEventArgs e)
        {
            File.WriteAllText("last", txtPesquisar.Text);
        }

        private void Form5_Load(object sender, EventArgs e)
        {
            if (File.Exists("last"))
            {
                txtPesquisar.Text = File.ReadAllText("last");
                txtResult.Text = Pesquisar(txtPesquisar.Text);
            }
        }


        [CanRegexParse]
        public class Encomenda
        {
            [RegexParse(@"<span class=""textNormalBlack"">.*?</p>(.*?)<br />", Grupo = 1)]
            public string StatusEncomenda { get; set; }
        }
    }
}
